package com.example.flight.service;

import com.alibaba.fastjson.JSONObject;
import com.example.flight.generate.Source2Dest;
import com.example.flight.generate.TuNiuFlightBean;
import com.example.flight.generate.TuNiuFlightDetail;
import com.example.flight.util.DateUtil;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.text.ParseException;
import java.util.*;

/**
 * @Author: leo
 * @date: 2021/7/2
 */
public class TuNiuService {

    public static String cookie = "_ga=GA1.2.1672640433.1625218282; _tacau=MCxjNmU1NzJmOS01NDViLTRkYTktYWYyNy03ZjEwODgxZWJlMzEs; _tact=MWNiODUxM2MtNGNkYi0wYjMzLTM4NzEtMmE5ZjM0NzI4ZGYx; _tacz2=taccsr%3D%28direct%29%7Ctacccn%3D%28none%29%7Ctaccmd%3D%28none%29%7Ctaccct%3D%28none%29%7Ctaccrt%3D%28none%29; tuniu_partner=MTAxLDAsLDlmZDgyZThjYTZkNGMwMTlmZTUyNzdlYjJmNTcxYzQ1; tuniuuser_citycode=NjE5; p_phone_400=4007-999-999; p_phone_level=0; p_global_phone=%2B0086-25-8685-9999; tuniuuser_id=2000166482; _gid=GA1.2.308569835.1625449453; simpwd15118139314=false; promptFlag659541=true; _tacc=1; company=%E5%A6%8D%E4%B8%BD%E5%8C%96%E5%A6%86%E5%93%81%EF%BC%88%E4%B8%AD%E5%9B%BD%EF%BC%89%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8-%E9%A2%84%E5%AD%98%3B12489%3B%E9%BB%84%E6%98%A5%E9%A6%99%3B659541%3B2; isLogined=true; ssoUser=7573d21b118856f9264eab31c140ff23; tuniuuser_force_logout=1625454495000; tuniuuser_cust_type=NQ%3D%3D; OLBSESSID=g8p5a3cbj482m3ktribbpjip77; tuniuuser=MjAwMDE2NjQ4Mizpu4TmmKXpppks6buE5pil6aaZLDAsMTYyNTQ1NDQ5Nyw4ODYxNjJlZTY1Y2Q2ZGQyNzE1NDhkZmU5MDI3YTU0Yg%3D%3D; tuniuuser_name=6buE5pil6aaZ; SESSION=e8d8f69d-51da-4600-9302-95f6d6fa3a18; _gat=1; _taca=1625218281542.1625454490634.1625463226765.4; _tacb=NDM5NGQ2ZmItYTRhZS05ZWViLTdlNGYtMGM0ZWRmNjU3MTNi";

    public static void main(String[] args) throws Exception {
        List<Source2Dest> list = source2DestList();
        list.stream().forEach(s->{



            String dCity = s.getDCity();
            String aCity = s.getACity();

            JSONObject jsonObject1 = null;
            try {
                jsonObject1 = firstSearch(dCity, aCity);
            } catch (IOException e) {
                e.printStackTrace();
            }
            TuNiuFlightBean tuNiuFlightBean1 = jsonObject1.toJavaObject(TuNiuFlightBean.class);

            while (tuNiuFlightBean1.getCode()==780003004){
                try {
                    jsonObject1 = firstSearch(dCity, aCity);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                tuNiuFlightBean1 = jsonObject1.toJavaObject(TuNiuFlightBean.class);
            }
            int channelCount = tuNiuFlightBean1.getData().getChannelCount();


            JSONObject jsonObject = null;
            try {
                jsonObject = httpPost(channelCount,dCity, aCity);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            TuNiuFlightBean tuNiuFlightBean = jsonObject.toJavaObject(TuNiuFlightBean.class);
            if (tuNiuFlightBean.getCode()==780003004){
                System.out.println(dCity+"$"+aCity+"$"+"空"+"$空");
//                try {
//                    jsonObject = httpPost(dCity, aCity);
//                } catch (IOException ex) {
//                    ex.printStackTrace();
//                }
//                tuNiuFlightBean = jsonObject.toJavaObject(TuNiuFlightBean.class);
            }else {

                List<TuNiuFlightBean.DataBean.FlightAndResourceInfosBean> flightAndResourceInfos = tuNiuFlightBean.getData().getFlightAndResourceInfos();
                Optional<TuNiuFlightBean.DataBean.FlightAndResourceInfosBean> bean = flightAndResourceInfos.stream().filter(e -> {
                    TuNiuFlightBean.DataBean.FlightAndResourceInfosBean.FlightInfoBean flightInfo = e.getFlightInfo();
                    try {
                        if (DateUtil.isEffectiveDate(flightInfo.getDepartureTime())) {
                            return true;
                        }
                    } catch (ParseException ex) {
                        ex.printStackTrace();
                    }
                    return false;
                }).findFirst();
                if (bean.isPresent()){
                    TuNiuFlightBean.DataBean.FlightAndResourceInfosBean flightAndResourceInfosBean = bean.get();
                    String flightNos = flightAndResourceInfosBean.getFlightInfo().getFlightNos();

                    String queryId = tuNiuFlightBean.getData().getQueryId();

                    JSONObject flightDetail = getFlightDetail(queryId, flightNos);
                    TuNiuFlightDetail tuNiuFlightDetail = flightDetail.toJavaObject(TuNiuFlightDetail.class);
                    List<TuNiuFlightDetail.DataBean.ResourceInfosBean> resourceInfos = tuNiuFlightDetail.getData().getResourceInfos();
                    while (resourceInfos.isEmpty()){
                        flightDetail = getFlightDetail(queryId, flightNos);
                        tuNiuFlightDetail = flightDetail.toJavaObject(TuNiuFlightDetail.class);
                        resourceInfos = tuNiuFlightDetail.getData().getResourceInfos();
                    }
                    int adultSalePrice = tuNiuFlightDetail.getData().getResourceInfos().get(0).getJourneyPrices().get(0).getPriceDetail().getAdultSalePrice();
                    double adultDiscount = tuNiuFlightDetail.getData().getResourceInfos().get(0).getJourneyPrices().get(0).getPriceDetail().getAdultDiscount();

                    System.out.println(dCity+"$"+aCity+"$"+adultDiscount+"$"+adultSalePrice);
                }else {
                    System.out.println(dCity+"$"+aCity+"$"+"空"+"$空");
                }
            }

        });


    }


    public static List<Source2Dest> source2DestList(){
        List<Source2Dest> list = new ArrayList<>();
        Source2Dest info ;
        info = new Source2Dest("鞍山","成都");
        list.add(info);
        info = new Source2Dest("北京","成都");
        list.add(info);
        info = new Source2Dest("北京","青岛");
        list.add(info);
        info = new Source2Dest("北京","深圳");
        list.add(info);
        info = new Source2Dest("成都","北京");
        list.add(info);
        info = new Source2Dest("成都","哈尔滨");
        list.add(info);
        info = new Source2Dest("成都","上海");
        list.add(info);
        info = new Source2Dest("成都","深圳");
        list.add(info);
        info = new Source2Dest("成都","太原");
        list.add(info);
        info = new Source2Dest("贵阳","深圳");
        list.add(info);
        info = new Source2Dest("哈尔滨","深圳");
        list.add(info);
        info = new Source2Dest("杭州","深圳");
        list.add(info);
        info = new Source2Dest("合肥","深圳");
        list.add(info);
        info = new Source2Dest("济南","深圳");
        list.add(info);
        info = new Source2Dest("昆明","深圳");
        list.add(info);


        info = new Source2Dest("南京",	"深圳");
        list.add(info);
        info = new Source2Dest("南宁",	"深圳");
        list.add(info);
        info = new Source2Dest("上海",	"深圳");
        list.add(info);
        info = new Source2Dest("深圳",	"北京");
        list.add(info);
        info = new Source2Dest("深圳",	"成都");
        list.add(info);
        info = new Source2Dest("深圳",	"赣州");
        list.add(info);
        info = new Source2Dest("深圳",	"贵阳");
        list.add(info);
        info = new Source2Dest("深圳",	"杭州");
        list.add(info);
        info = new Source2Dest("深圳",	"合肥");
        list.add(info);
        info = new Source2Dest("深圳",	"济南");
        list.add(info);
        info = new Source2Dest("深圳",	"昆明");
        list.add(info);
        info = new Source2Dest("深圳",	"临沂");
        list.add(info);
        info = new Source2Dest("深圳",	"南京");
        list.add(info);
        info = new Source2Dest("深圳",	"南宁");
        list.add(info);
        info = new Source2Dest("深圳",	"南通");
        list.add(info);
        info = new Source2Dest("深圳",	"宁波");
        list.add(info);
        info = new Source2Dest("深圳",	"青岛");
        list.add(info);
        info = new Source2Dest("深圳",	"上海");
        list.add(info);
        info = new Source2Dest("深圳",	"沈阳");
        list.add(info);
        info = new Source2Dest("深圳",	"石家庄");
        list.add(info);
        info = new Source2Dest("深圳",	"太原");
        list.add(info);
        info = new Source2Dest("深圳",	"天津");
        list.add(info);
        info = new Source2Dest("深圳",	"温州");
        list.add(info);
        info = new Source2Dest("深圳",	"武汉");
        list.add(info);
        info = new Source2Dest("深圳",	"西安");
        list.add(info);
        info = new Source2Dest("深圳",	"银川");
        list.add(info);
        info = new Source2Dest("深圳",	"长春");
        list.add(info);
        info = new Source2Dest("深圳",	"郑州");
        list.add(info);
        info = new Source2Dest("深圳",	"重庆");
        list.add(info);
        info = new Source2Dest("沈阳",	"成都");
        list.add(info);
        info = new Source2Dest("沈阳",	"深圳");
        list.add(info);
        info = new Source2Dest("南京",	"深圳");
        list.add(info);
        info = new Source2Dest("石家庄","深圳");
        list.add(info);
        info = new Source2Dest("太原",	"深圳");
        list.add(info);
        info = new Source2Dest("天津",	"深圳");
        list.add(info);
        info = new Source2Dest("温州",	"深圳");
        list.add(info);
        info = new Source2Dest("武汉",	"深圳");
        list.add(info);
        info = new Source2Dest("西安",	"深圳");
        list.add(info);
        info = new Source2Dest("银川",	"深圳");
        list.add(info);
        info = new Source2Dest("银川",	"重庆");
        list.add(info);
        info = new Source2Dest("长春",	"成都");
        list.add(info);
        info = new Source2Dest("长春",	"深圳");
        list.add(info);
        info = new Source2Dest("郑州",	"深圳");
        list.add(info);
        info = new Source2Dest("重庆",	"深圳");
        list.add(info);
        info = new Source2Dest("重庆",	"银川");
        list.add(info);
        return list;
    }

    public static JSONObject getFlightDetail(String queryId, String flightNos){
        String url = "https://tmc.tuniu.com/flight/v3/query/more/detail";
        // 获取请求连接
        Connection con = Jsoup.connect(url).ignoreContentType(true);
        Map<String, String> cityCodeMap = getCityCodeMap();
        String jsonContent ="{\n" +
                "    \"flightNos\": \""+flightNos+"\",\n" +
                "    \"queryId\": \""+queryId+"\",\n" +
                "    \"cabinTypeList\": [],\n" +
                "    \"cabinTypeBackList\": []\n" +
                "}";

        con.requestBody(jsonContent);
        // 插入cookie（头文件形式）
        con.header("cookie", cookie);
        con.header(
                "user-agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36");
        Document doc = null;
        try {
            doc = con.header("Content-Type", "application/json").post();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Element body = doc.body();
        JSONObject json = JSONObject.parseObject(body.text());
        return json;
    }

    public static JSONObject httpPost(int channelCount, String dCityName, String aCityName) throws IOException {
        String url = "https://tmc.tuniu.com/flight/v3/search";
        // 获取请求连接
        Connection con = Jsoup.connect(url).ignoreContentType(true);
        Map<String, String> cityCodeMap = getCityCodeMap();
        String jsonContent ="{\n" +
                "    \"forCorp\": \"1\",\n" +
                "    \"segments\": [\n" +
                "        {\n" +
                "            \"depCityIataCode\": \""+cityCodeMap.get(dCityName)+"\",\n" +
                "            \"arrCityIataCode\": \""+cityCodeMap.get(aCityName)+"\",\n" +
                "            \"depDate\": \"2021-07-15\"\n" +
                "        }\n" +
                "    ],\n" +
                "channelCount: "+channelCount+","+
//                "    \"channelCount\": 10,\n" +
                "    \"pollTag\": 1,\n" +
                "    \"upFlightNo\": \"\",\n" +
                "    \"sortType\": 0\n" +
                "}";

        con.requestBody(jsonContent);
        // 插入cookie（头文件形式）
        con.header("cookie", cookie);
        con.header(
                "user-agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36");
        Document doc = con.header("Content-Type", "application/json").post();
        Element body = doc.body();
        JSONObject json = JSONObject.parseObject(body.text());
        return json;
    }

    public static JSONObject firstSearch(String dCityName, String aCityName) throws IOException {
        String url = "https://tmc.tuniu.com/flight/v3/search";
        // 获取请求连接
        Connection con = Jsoup.connect(url).ignoreContentType(true);
        Map<String, String> cityCodeMap = getCityCodeMap();
        String jsonContent ="{\n" +
                "    \"forCorp\": \"1\",\n" +
                "    \"segments\": [\n" +
                "        {\n" +
                "            \"depCityIataCode\": \""+cityCodeMap.get(dCityName)+"\",\n" +
                "            \"arrCityIataCode\": \""+cityCodeMap.get(aCityName)+"\",\n" +
                "            \"depDate\": \"2021-07-15\"\n" +
                "        }\n" +
                "    ],\n" +
                "\"channelCount\": \"\""+","+
//                "    \"channelCount\": 10,\n" +
                "    \"pollTag\": 1,\n" +
                "    \"upFlightNo\": \"\",\n" +
                "    \"sortType\": 0\n" +
                "}";

        jsonContent = "{\n" +
                "    \"forCorp\": \"1\",\n" +
                "    \"segments\": [\n" +
                "        {\n" +
                "             \"depCityIataCode\": \""+cityCodeMap.get(dCityName)+"\",\n" +
                "            \"arrCityIataCode\": \""+cityCodeMap.get(aCityName)+"\",\n" +
                "            \"depDate\": \"2021-07-15\"\n" +
                "        }\n" +
                "    ],\n" +
                "    \"channelCount\": \"\",\n" +
                "    \"pollTag\": 0,\n" +
                "    \"upFlightNo\": \"\",\n" +
                "    \"sortType\": 0\n" +
                "}";

        con.requestBody(jsonContent);
        // 插入cookie（头文件形式）
        con.header("cookie", cookie);
        con.header(
                "user-agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36");
        Document doc = con.header("Content-Type", "application/json").post();
        Element body = doc.body();
        JSONObject json = JSONObject.parseObject(body.text());
        return json;
    }

    public static Map<String,String> getCityCodeMap(){
        Map<String,String > map = new HashMap<>();
        map.put("南宁" , "NNG");
        map.put("济南" , "TNA");
        map.put("昆明" , "KMG");
        map.put("临沂" , "LYI");
        map.put("赣州" , "KOW");
        map.put("宁波" , "NGB");
        map.put("重庆" , "CKG");
        map.put("石家庄" , "SJW");
        map.put("贵阳" , "KWE");
        map.put("长春" , "CGQ");
        map.put("哈尔滨" , "HRB");
        map.put("鞍山" , "AOG");
        map.put("合肥" , "HFE");
        map.put("天津" , "TSN");
        map.put("温州" , "WNZ");
        map.put("青岛" , "TAO");
        map.put("杭州" , "HGH");
        map.put("成都" , "CTU");
        map.put("上海" , "SHA");
        map.put("沈阳" , "SHE");
        map.put("南通" , "NTG");
        map.put("武汉" , "WUH");
        map.put("深圳" , "SZX");
        map.put("银川" , "INC");
        map.put("西安" , "SIA");
        map.put("郑州" , "CGO");
        map.put("太原" , "TYN");
        map.put("北京" , "BJS");
        map.put("南京" , "NKG");
        return map;
    }


}
